Ext.define('BISC.view.FilterManagerRulesInput', {
    extend: 'Ext.form.Panel',
    alias: ['widget.filtermanagerrulesinput'],
    id: 'formAddFilterComponents',
    title: 'Filters',
    border: false,
    bodyPadding: 10,
    initComponent: function() {
        var me = this;

        Ext.applyIf(me, {
            items: [
                {
                    xtype: 'panel',
                    border: false,
                    id: 'filterTokensPanel',
                    data: me.mainForm.filter.filters,
                    tpl: new Ext.XTemplate('<table><tr><th></th><th class="thStyle">Filter</th><tpl for=".">' +
                                    '<tr>' +
                                        '<td><button class="removeTokenBtn" filter-id="{id}">Remove</button></td>' +
                                        '<td>{text}</td>' +
                                    '</tr>' +
                                '</tpl></table>'
                    ),
                    scope: me,
                    listeners: {
                        afterrender: function() {
                            me.addDataviewItemListeners();
                        }
                    }
                },
                {
                    xtype: 'component',
                    html: 'Automatic attribution only occurs when <span style="font-weight: bold;">all</span> the filters match the image. Filters match all images by default.<br><div id="addCmpError" style="color: red; padding: 5px; font-weight: bold;"></div>'
                },
                {
                    xtype: 'combo',
                    fieldLabel: 'Add filter',
                    queryMode: 'local',
                    displayField: 'value',
                    valueField: 'key',
                    store: Ext.create('Ext.data.Store', {
                        fields: ['key', 'value'],
                        data: [
                            {key: 'keyword', value: 'Keyword'},
                            {key: 'datetime', value: 'Exact Date or Range'}
                        ]
                    }),
                    listeners: {
                        change: function( combo, newVal, oldVal, opts ) {
                            var oldF = Ext.getCmp('addCmp'+oldVal);
                            var newF = Ext.getCmp('addCmp'+newVal);
                            if ( oldF ) oldF.hide();
                            if ( newF ) newF.show();
                        }
                    }
                },
                {
                    xtype: 'panel',
                    border: false,
                    hidden: true,
                    id: 'addCmpkeyword',
                    singleDate: true,
                    items: [
                        {
                            xtype: 'textfield',
                            id: 'ruleKeywordField',
                            fieldLabel: 'Add keyword',
                            enableKeyEvents: true,
                            listeners: {
                                keypress: function( field, e, opts ) {
                                    if ( e.keyCode == e.ENTER ) {
                                        var value = field.getValue();
                                        var tempFilter = {
                                            id: me.mainForm.filter.tempId++,
                                            type: 'keyword',
                                            raw: value,
                                            text: 'Keyword: ' + value
                                        };
                                        if ( value != '' ) {
                                            if ( me.filterExists( tempFilter ) ) {
                                                Ext.get('addCmpError').update('Filter already added.');
                                            } else {
                                                me.mainForm.filter.filters.push( tempFilter );
                                                Ext.getCmp('filterTokensPanel').update( me.mainForm.filter.filters );
                                                Ext.getCmp('formAddFilterComponents').addDataviewItemListeners();
                                                Ext.get('addCmpError').update('');
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        {
                            xtype: 'button',
                            text: 'Add Date Filter',
                            scope: me,
                            handler: function() {
                                var value = Ext.getCmp('ruleKeywordField').getValue();
                                var tempFilter = {
                                    id: me.mainForm.filter.tempId++,
                                    type: 'keyword',
                                    raw: value,
                                    text: 'Keyword: ' + value
                                };
                                if ( value != '' ) {
                                    if ( me.filterExists( tempFilter ) ) {
                                        Ext.get('addCmpError').update('Filter already added.');
                                    } else {
                                        me.mainForm.filter.filters.push( tempFilter );
                                        Ext.getCmp('filterTokensPanel').update( me.mainForm.filter.filters );
                                        Ext.getCmp('formAddFilterComponents').addDataviewItemListeners();
                                        Ext.get('addCmpError').update('');
                                    }
                                }
                            }
                        }
                    ]
                },
                {
                    xtype: 'panel',
                    border: false,
                    hidden: true,
                    id: 'addCmpdatetime',
                    singleDate: true,
                    items: [
                        {
                            xtype: 'component',
                            html: 'Add date range'
                        },
                        {
                            xtype: 'combo',
                            id: 'addCmpDateType',
                            queryMode: 'local',
                            displayField: 'value',
                            valueField: 'key',
                            value: 'added',
                            store: Ext.create('Ext.data.Store', {
                                fields: ['key', 'value'],
                                data: [
                                    {key: 'added', value: 'Date Added'},
                                    {key: 'modified', value: 'Date Modified'}
                                ]
                            })
                        },
                        {
                            xtype: 'datefield',
                            id: 'addCmpdatetime1',
                            fieldLabel: 'Exact date'
                        },
                        {
                            xtype: 'checkbox',
                            fieldLabel: 'Use date range?',
                            listeners: {
                                change: function( cb, newVal, oldVal, opts ) {
                                    if ( newVal ) {
                                        Ext.getCmp('addCmpdatetime').singleDate = false;
                                        Ext.getCmp('addCmpdatetime1').setFieldLabel( 'Minimum date' );
                                        Ext.getCmp('addCmpdatetime2').enable();
                                    } else {
                                        Ext.getCmp('addCmpdatetime').singleDate = true;
                                        Ext.getCmp('addCmpdatetime1').setFieldLabel( 'Exact date' );
                                        Ext.getCmp('addCmpdatetime2').disable();
                                    }
                                }
                            }
                        },
                        {
                            xtype: 'datefield',
                            id: 'addCmpdatetime2',
                            fieldLabel: 'Maximum date',
                            disabled: true
                        },
                        {
                            xtype: 'button',
                            text: 'Add Date Filter',
                            scope: me,
                            handler: function() {
                                var tempFilter = {
                                    id: me.mainForm.filter.tempId++,
                                    type: ( Ext.getCmp('addCmpdatetime').singleDate ) ? 'date' : 'daterange',
                                    type2: Ext.getCmp('addCmpDateType').getValue(),
                                    raw: Ext.Date.format( Ext.getCmp('addCmpdatetime1').getValue(), 'm-d-Y'),
                                    raw2: Ext.Date.format( Ext.getCmp('addCmpdatetime2').getValue(), 'm-d-Y'),
                                    text: ''
                                };
                                tempFilter.text = me.parseTokenRawValue( tempFilter );

                                if ( tempFilter.type == 'date' ) {
                                    if ( tempFilter.raw == '' ) {
                                        Ext.get('addCmpError').update('Please enter a date.');
                                    } else {
                                        if ( me.filterExists( tempFilter ) ) {
                                            Ext.get('addCmpError').update('Date already exists.');
                                        } else {
                                            me.mainForm.filter.filters.push( tempFilter );
                                            Ext.getCmp('filterTokensPanel').update( me.mainForm.filter.filters );
                                            Ext.getCmp('formAddFilterComponents').addDataviewItemListeners();
                                            Ext.get('addCmpError').update('');
                                        }
                                    }
                                } else {
                                    if ( tempFilter.raw == '' || tempFilter.raw2 == '' ) {
                                        Ext.get('addCmpError').update('Please enter a minimum and maximum date.');
                                        return;
                                    }
                                    if ( tempFilter.raw > tempFilter.raw2 ) {
                                        Ext.get('addCmpError').update('Minimum date must be lower than the maximum date.');
                                    } else {
                                        if ( me.filterExists( tempFilter ) ) {
                                            Ext.get('addCmpError').update('Date range already exists.');
                                        } else {
                                            me.mainForm.filter.filters.push( tempFilter );
                                            Ext.getCmp('filterTokensPanel').update( me.mainForm.filter.filters );
                                            Ext.getCmp('formAddFilterComponents').addDataviewItemListeners();
                                            Ext.get('addCmpError').update('');
                                        }
                                    }
                                }
                            }
                        }
                    ]
                }
            ]
        });

        me.callParent(arguments);
    },
    filterExists: function( newToken ) {
        var flag = false;
        Ext.each( this.mainForm.filter.filters, function( filter ) {
            if ( newToken.type == 'daterange' ) {
                if ( filter.raw == newToken.raw && filter.raw2 == newToken.raw2 ) flag = true;
            } else {
                if ( filter.raw == newToken.raw ) flag = true;
            }
        });
        return flag;
    },
    parseTokenRawValue: function( rule ) {
        if ( rule.type == 'date' ) {
            return 'Date ' + rule.type2 + ' is ' + rule.raw;
        }
        if ( rule.type == 'daterange' ) {
            return 'Date ' + rule.type2 + ' is between ' + rule.raw + ' and ' + rule.raw2;
        }
        if ( rule.type == 'keyword' ) {
            return 'Keyword: ' + rule.raw;
        }
    },
    addDataviewItemListeners: function() {
        Ext.getCmp('filterTokensPanel').getEl().select('.removeTokenBtn').each( function( el ) {
            el.on( 'click', function( e, el, opts ) {
                var filterId = el.getAttribute( 'filter-id' );
                var filters = Ext.getCmp('createFilterPanel').filter.filters;
                Ext.each( filters, function( filter ) {
                    if ( filter.id == filterId ) {
                        filters.splice( filters.indexOf( filter ), 1 );
                        Ext.getCmp('filterTokensPanel').update( filters );
                        Ext.getCmp('formAddFilterComponents').addDataviewItemListeners();
                        return;
                    }
                });
            });
        });
    }
});
